import React from 'react';
import {Table, Input, Select, Form, Box, Button, Card, DatePicker, Message, Radio, Collapse,Upload, Switch, Dialog, Grid } from '@alifd/next';
import styles from './index.module.scss';

import {detailV, update} from '@/api/VersionAPI'
import {upLoadImage, upLoadApk} from '@/api/CommonAPI'
import {getOptionValue} from '@/utils/tool'
import JsonUtils from '@/utils/JsonUtils'
const {Row, Col} = Grid;
const FormItem = Form.Item;
const Panel = Collapse.Panel;
const formItemLayout = {
  colSpan: 12,
};

const formItemLayout_two = {
    colSpan: 6,
};
const formItemLayout_three = {
    colSpan: 4,
};

const DEFAULT_DATA = {
    id: '',
    name:'',
    code:'',
    versionCode:'',
    versionNum:'',
    versionFlag:'',
    osType:'0',
    osName:'0',
    verExplain: '',
    releaseState: '0',
    releaseStateName:'',
    uploadFileId : '',
    downLoadUrl: '',
    appMd5: '',
    appSize:'',
    upLoadRemark :'',
    state:'0',
    releaseTime:'',
    createTime: '',
    createId: '',
    createName: '',
    updateTime: '',
    updateId: '',
    updateName: '',
    logoImages: [],
  };

class UpdateVersion extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            postData: DEFAULT_DATA,
            visible: false,
            apkData:[],
            statesDataOption: [],
            osTypeDataOption:[],
            versionFlagDataOptin:[],
        };
    }

    
    // 初始化方法
    componentDidMount(){
        this.props.onRef(this)
    };

    // 1 打开弹框
    onOpen = (key, statesData, osTypeData, versionFlagData) => {
        this.resetForm(); 
        detailV(key).then((data)=>{
            if(data){
                // 遍历赋值
                for(var k in data){
                    DEFAULT_DATA[k] = data[k]
                }
                // 处理图片预览
                data.logoImages.map((item)=>{
                    item.state = 'done'
                    item.uid = item.id
                })
                // 封装APK上传信息
                let _apkData = [{
                    id: data.uploadFileId,
                    state: 'done',
                    name: data.name,
                    url: data.downLoadUrl,
                    downloadURL: data.downLoadUrl,
                    size: data.appSize,
                }]
                this.setState({
                    statesDataOption: statesData,
                    osTypeDataOption: osTypeData,
                    versionFlagDataOptin: versionFlagData,
                    apkData: _apkData,
                    postData: DEFAULT_DATA,
                    visible: true,
                })
            }else{
                Message.error("加载数据失败...")
            }
        });
    };
    // 2 关闭弹框
    onClose = () => {
        this.setState({
            visible: false
        })
    };
    // 3 修改表单信息
    formChange = values => {
        this.setState({
            postData: values
        })
    };

    // 4 改变表单--代码
    changeFormCode= (v) => {
        DEFAULT_DATA.code = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };
    // 5 改变表单--版本级别
    changeVersionFlag= (v) => {
        DEFAULT_DATA.versionFlag = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };   
    // 6 改变表单--适配系统类型
    changeOsType= (v) => {
        DEFAULT_DATA.osType = v;
        DEFAULT_DATA.osName = getOptionValue(this.state.osTypeDataOption,v);
        this.setState({
            postData: DEFAULT_DATA,
        })
    };   
    // 7 改变表单--发布说明
    changeFormVerExplain= (v) => {
        DEFAULT_DATA.verExplain = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };   
    // 8 改变表单--备注
    changeFormRemark= (v) => {
        DEFAULT_DATA.remark = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };

    /**
     * 上传图片
     * @param {*} info 
     */
    upLoadImageBegin = (info) => {
        // 1 调用上传API
        let filename = info.filename;
        console.log('info is:::', filename)
        upLoadImage( 'file', info.file).then((data)=>{
            if(data){
                // 2 
                if(filename == 'logoImages'){
                    DEFAULT_DATA.logoImages.push(data)
                } 
                // 4 回显信息
                let onSuccessInfo = {
                    success: true,
                    uid: data.id,
                    url: data.url,
                }
                console.log('upLoadImageBegin DEFAULT_DATA is:::', DEFAULT_DATA)
                info.onSuccess(onSuccessInfo);
            }
        });
    };
    /**
     * 上传APK
     * @param {*} info 
     */
    upLoadApkBegin = (info) => {
        // 1 调用上传API
        let filename = info.filename;
        console.log('info is:::', filename)
        upLoadApk(info.file).then((data)=>{
            if(data){
                // 2 赋值
                DEFAULT_DATA.versionCode= data.versionCode
                DEFAULT_DATA.versionNum= data.versionName
                DEFAULT_DATA.appMd5= data.appMd5
                DEFAULT_DATA.appSize= data.appSize
                DEFAULT_DATA.name= data.appName
                DEFAULT_DATA.uploadFileId = data.fileId
                DEFAULT_DATA.downLoadUrl = data.downLoadUrl
                DEFAULT_DATA.osType = data.osType
                DEFAULT_DATA.osName = getOptionValue(this.state.osTypeDataOption, data.osType)
                DEFAULT_DATA.upLoadRemark = JsonUtils.jsonToString(data)
                this.setState({
                    postData: DEFAULT_DATA,
                })
                // 3 回显信息
                let onSuccessInfo = {
                    success: true,
                    uid: data.fileId,
                    url: data.downLoadUrl,
                }
                console.log('upLoadImageBegin DEFAULT_DATA is:::', DEFAULT_DATA)
                info.onSuccess(onSuccessInfo);
            }else{
                Message.error('上传APK错误');
            }
        });
    };
    // 删除图片信息
    onRemoveImage =(filename, info) =>{
        console.log('onRemoveImage info is:::', info)
        console.log('onRemoveImage filename is:::', filename)
    }
    // 删除图片信息
    onRemoveMainImage =(info) =>{
        console.log('onRemoveImage info is:::', info)
    }
    // 提交表单信息
    onSubmit = (values, errors) => {
        if (errors) {
          console.log('errors', errors);
          return;
        }
        // 调用修改API接口
        update(DEFAULT_DATA).then((flag)=>{
            if(flag){
                Message.success('提交成功');
                this.resetForm(); // 清空表单源数据
                this.onClose();
                this.props.onFreshList();
            }else{
                return
            }
        });
    };
    /**
     * 重置表单
     */
    resetForm = ()=>{
        DEFAULT_DATA.id = '',
        DEFAULT_DATA.name ='',
        DEFAULT_DATA.code ='',
        DEFAULT_DATA.versionCode ='',
        DEFAULT_DATA.versionNum ='',
        DEFAULT_DATA.versionFlag ='',
        DEFAULT_DATA.osType ='0',
        DEFAULT_DATA.osName ='0',
        DEFAULT_DATA.verExplain = '',
        DEFAULT_DATA.releaseState = '0',
        DEFAULT_DATA.releaseStateName ='',
        DEFAULT_DATA.downLoadUrl = '',
        DEFAULT_DATA.uploadFileId ='',
        DEFAULT_DATA.appMd5 = '',
        DEFAULT_DATA.appSize ='',
        DEFAULT_DATA.upLoadRemark ='',
        DEFAULT_DATA.state ='0',
        DEFAULT_DATA.releaseTime ='',
        DEFAULT_DATA.createTime = '',
        DEFAULT_DATA.createId = '',
        DEFAULT_DATA.createName = '',
        DEFAULT_DATA.updateTime = '',
        DEFAULT_DATA.updateId = '',
        DEFAULT_DATA.updateName = '',
        DEFAULT_DATA.logoImages = [],
        this.setState({
            DEFAULT_DATA,
        })
    }

    onPreview(info){
        console.log('onPreview:::', info);
    }

    render(){
        return (
            <div > 
                <Dialog title="修改版本信息" visible={this.state.visible} footer ={false}  onClose={this.onClose} style={{width: '40%'}} >
                    <Card free className={styles.TwoColumnForm}>
                    <Card.Content>
                        <Form responsive fullWidth value={this.state.postData} labelAlign="top">
                            <FormItem {...formItemLayout_two} label="APP名称" required requiredMessage="必填">
                                <Input value={this.state.postData.name} placeholder="通过上传APK自动识别" disabled />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="代码" required requiredMessage="必填">
                                <Input placeholder="请输入代码" name="code" onChange={this.changeFormCode} />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="强制更新"  required requiredMessage="必填">
                                <Select name='versionFlag' placeholder="选择更新级别" dataSource= {this.state.versionFlagDataOptin || []}  onChange={this.changeVersionFlag}  hasClear/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="系统类型"  required requiredMessage="必填">
                                <Select value={this.state.postData.osType}  placeholder="通过上传APK自动识别" dataSource= {this.state.osTypeDataOption || []}  disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout} label="发布说明" required requiredMessage="必填">
                                <Input.TextArea placeholder="请输入发布说明" name="verExplain" onChange={this.changeFormVerExplain} />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="版本号"  required requiredMessage="必填">
                                <Select value={this.state.postData.versionNum} placeholder="通过上传APK自动识别"  disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="版本代码"  required requiredMessage="必填">
                                <Select value={this.state.postData.versionCode} placeholder="通过上传APK自动识别" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="APP大小"  required requiredMessage="必填">
                                <Select value={this.state.postData.appSize} placeholder="通过上传APK自动识别"  disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="MD5"  required requiredMessage="必填">
                                <Select value={this.state.postData.appMd5} placeholder="通过上传APK自动识别" disabled/>
                            </FormItem>

                            <FormItem {...formItemLayout_two} label="发布宣传图：">
                                <Upload.Card name="logoImages" listType="card"
                                    accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp"
                                    request={this.upLoadImageBegin}
                                    onRemove={this.onRemoveMainImage}
                                    onPreview={this.onPreview}
                                    limit={2}
                                />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="上传APK：">
                                <Upload name="fileApk" listType="text"
                                    accept="file/apk"
                                    request={this.upLoadApkBegin}
                                    onRemove={this.onRemoveImage}
                                    defaultValue={this.state.apkData}
                                    limit={1}>
                                    <Button type="primary" style={{margin: '0 0 10px'}}>上传</Button>
                                </Upload>
                                
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="状态" required requiredMessage="必填">
                                <Input name='releaseStateName' disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="发布时间">
                                <Input name="publishTime" disabled/>
                            </FormItem>

                            <FormItem {...formItemLayout} label="备注">
                                <Input.TextArea placeholder="请输入备注" name="remark" onChange={this.changeFormRemark}/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="创建人">
                                <Input name="createName" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="创建时间">
                                <Input name="createTime" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="最后一次修改人">
                                <Input name="updateName" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="最后一次时间">
                                <Input name="updateTime" disabled/>
                            </FormItem>
                            <FormItem colSpan={12} style={{marginLeft:'35%'}}>
                                <Box spacing={8} direction="row" align="center">
                                    <Form.Submit type="primary" onClick={this.onSubmit} validate>提交</Form.Submit>
                                    <Button onClick={this.onClose} type="secondary">取消</Button>
                                </Box>
                            </FormItem>
                        </Form>
                    </Card.Content>
                    </Card>
                </Dialog>
            </div>
        );
    }
}
export default UpdateVersion;
